/*
 * Copyright 2003,2004 The Apache Software Foundation
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package eu.jakubiak.jpa.translator.serializer;

import eu.jakubiak.utils.base64.Base64;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 *
 * @author Antek
 */
public class ObjectStreamSerializer implements Serializer {
    
    public static final String CHARSET = "UTF-8";

    /**
     * Simply java deserialization from string
     * @param type
     * @param string
     * @return
     */
    @Override
    public <T> T deserialize(Class<T> type, String string) {
        try {
            ByteArrayInputStream bais = new ByteArrayInputStream(Base64.decode(string));
            ObjectInputStream ois = new ObjectInputStream(bais);
            T ret = (T)ois.readObject();
            ois.close();
            bais.close();
            return ret;
        } catch(ClassNotFoundException ex) {
            throw new RuntimeException("Deserialization error",ex);
        } catch(IOException ex) {
            throw new RuntimeException("Deserialization error",ex);
        }
    }

    /**
     * Simply java serialization to string
     * @param object
     * @return
     */
    @Override
    public String serialize(Object object) {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(object);
            oos.flush();
            baos.flush();
            byte[] bytes = baos.toByteArray();
            oos.close();
            baos.close();
            return Base64.encodeBytes(bytes);
        } catch (IOException ex) {
            throw new RuntimeException("Serialization error",ex);
        }
    }

}
